	//
	//  LogFile.m
	//  GaCameraViewProject
	//
	//  Created by GikkiAres on 2020/4/8.
	//  Copyright © 2020 GikkiAres. All rights reserved.
	//

#import "JsFile.h"

@implementation JsFile


- (void)remove {
	self.isExisted = NO;
	[[NSFileManager defaultManager]removeItemAtPath:self.filePath error:nil];
		//    NSLog(@"Deleting file at path %@",self.filePath);
}

+ (JsFile *)fileWithFilePath:(NSString *)filePath {
	JsFile * file = [JsFile new];
	file.filePath = filePath;
	
	NSString * fileName = filePath.lastPathComponent;
	file.fileName = fileName;
	
	file.isExisted = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&file->_isDirectory];
	if(file.isExisted) {
		NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
		if (fileAttributes) {
			NSNumber *fileSize;
				//		NSString *fileOwner;
			NSDate *creationDate;
				//		NSDate *fileModDate;
				//文件大小
			if ((fileSize = [fileAttributes objectForKey:NSFileSize])) {
				file.fileSize = [fileSize intValue];
			}
				//文件创建日期
			if ((creationDate = [fileAttributes objectForKey:NSFileCreationDate])) {
				file.createdDate = creationDate;
			}
				//			//文件所有者
				//		if ((fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName])) {
				//			NSLog(@"Owner: %@\n", fileOwner);
				//		}
				//			//文件修改日期
				//		if ((fileModDate = [fileAttributes objectForKey:NSFileModificationDate])) {
				//			NSLog(@"Modification date: %@\n", fileModDate);
				//		}
		}
	}
	return file;
}

+ (NSMutableArray *)fileListInDirPath:(NSString *)dirPath {
	NSMutableArray <JsFile *>* marr = [NSMutableArray array];
	
	NSFileManager * fileManger = [NSFileManager defaultManager];
	NSArray * dirArray = [fileManger contentsOfDirectoryAtPath:dirPath error:nil];
	NSString * filePath = nil;
	for (NSString * fileName in dirArray) {
		filePath  = [dirPath stringByAppendingPathComponent:fileName];
		BOOL isDir = NO;
		[fileManger fileExistsAtPath:filePath isDirectory:&isDir];
		if(!isDir) {
			JsFile * file = [JsFile fileWithFilePath:filePath];
			[marr addObject:file];
		}
	}
	//排序,字典排序小的在前,大的在后,Ascending.
	//这里取反,大的在前.
	[marr sortUsingComparator:^NSComparisonResult(JsFile *  _Nonnull obj1, JsFile *  _Nonnull obj2) {
		NSComparisonResult result = [obj1.fileName compare:obj2.fileName];
		if(result == NSOrderedAscending) {
				//日期小的放后面.
			return NSOrderedDescending;
		}
		else {
			return NSOrderedAscending;
		}
	}];
	return marr;
}

@end

